package org.tao.lightningmq.broker.model;

import org.tao.lightningmq.broker.utils.ByteConvertUtil;

/**
 * @Author lht
 * @date 2025/1/4 - 21:50
 * @description: consumerQueue数据结构存储的最小单元对象
 */
public class ConsumeQueueDetailModel {

    private int commitLogFilename;
    private int msgIndex;
    private int msgLen;
    private int retryTimes;

    public int getCommitLogFilename() {
        return commitLogFilename;
    }

    public String getCommitLogFilenameStr() {
        return String.format("%08d", this.commitLogFilename);
    }

    public void setCommitLogFilename(int commitLogFilename) {
        this.commitLogFilename = commitLogFilename;
    }

    public int getMsgIndex() {
        return msgIndex;
    }

    public void setMsgIndex(int msgIndex) {
        this.msgIndex = msgIndex;
    }

    public int getMsgLen() {
        return msgLen;
    }

    public void setMsgLen(int msgLen) {
        this.msgLen = msgLen;
    }

    public int getRetryTimes() {
        return retryTimes;
    }

    public void setRetryTimes(int retryTimes) {
        this.retryTimes = retryTimes;
    }

    @Override
    public String toString() {
        return "ConsumeQueueDetailModel{" +
                "commitLogFilename=" + commitLogFilename +
                ", msgIndex=" + msgIndex +
                ", msgLen=" + msgLen +
                ", retryTimes=" + retryTimes +
                '}';
    }

    public byte[] convertToBytes() {
        byte[] commitLogFileNameBytes = ByteConvertUtil.intToBytes(commitLogFilename);
        byte[] msgIndexBytes = ByteConvertUtil.intToBytes(msgIndex);
        byte[] msgLengthBytes = ByteConvertUtil.intToBytes(msgLen);
        byte[] retryTimeBytes = ByteConvertUtil.intToBytes(retryTimes);
        byte[] finalBytes = new byte[16];
        int p = 0;
        for (int i = 0; i < 4; i++) {
            finalBytes[p++] = commitLogFileNameBytes[i];
        }
        for (int i = 0; i < 4; i++) {
            finalBytes[p++] = msgIndexBytes[i];
        }
        for (int i = 0; i < 4; i++) {
            finalBytes[p++] = msgLengthBytes[i];
        }
        for (int i = 0; i < 4; i++) {
            finalBytes[p++] = retryTimeBytes[i];
        }
        return finalBytes;
    }

    public void buildFromBytes(byte[] body) {
        this.setCommitLogFilename(ByteConvertUtil.bytesToInt(ByteConvertUtil.readInPos(body,0,4)));
        this.setMsgIndex(ByteConvertUtil.bytesToInt(ByteConvertUtil.readInPos(body,4,4)));
        this.setMsgLen(ByteConvertUtil.bytesToInt(ByteConvertUtil.readInPos(body,8,4)));
        this.setRetryTimes(ByteConvertUtil.bytesToInt(ByteConvertUtil.readInPos(body,12,4)));
    }
}
